<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>使用C语言实现服务器/客户端的TCP通信 - whowin - 发表我个人原创作品的技术博客</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="whowin" /><meta name="description" content="本文力求使用简单的描述说明一个服务器/客户端TCP通信的基本程序框架，使读者在这个框架下可以构建更加复杂的服务，文中给出了服务器端和客户端的实例源程序，本文适合网络编程的初学者阅读；本文的程序在ubuntu 20.04中编译运行成功，gcc版本号为：9.4.0
" /><meta name="keywords" content="linux, socket, hugo, dos" />






<meta name="generator" content="Hugo 0.97.3 with theme even" />


<link rel="canonical" href="https://whowin.gitee.io/post/blog/network/0012-tcp-server-client-implementation-in-c/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.e3fea119b1980e848b03dffbeddb11dd0fba483eed0e5f11870fb8e31f145bbd.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="使用C语言实现服务器/客户端的TCP通信" />
<meta property="og:description" content="本文力求使用简单的描述说明一个服务器/客户端TCP通信的基本程序框架，使读者在这个框架下可以构建更加复杂的服务，文中给出了服务器端和客户端的实例源程序，本文适合网络编程的初学者阅读；本文的程序在ubuntu 20.04中编译运行成功，gcc版本号为：9.4.0" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://whowin.gitee.io/post/blog/network/0012-tcp-server-client-implementation-in-c/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2023-01-06T16:43:29+08:00" />
<meta property="article:modified_time" content="2023-01-06T16:43:29+08:00" />

<meta itemprop="name" content="使用C语言实现服务器/客户端的TCP通信">
<meta itemprop="description" content="本文力求使用简单的描述说明一个服务器/客户端TCP通信的基本程序框架，使读者在这个框架下可以构建更加复杂的服务，文中给出了服务器端和客户端的实例源程序，本文适合网络编程的初学者阅读；本文的程序在ubuntu 20.04中编译运行成功，gcc版本号为：9.4.0"><meta itemprop="datePublished" content="2023-01-06T16:43:29+08:00" />
<meta itemprop="dateModified" content="2023-01-06T16:43:29+08:00" />
<meta itemprop="wordCount" content="5615">
<meta itemprop="keywords" content="Linux,Socket,网络编程,TCP," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="使用C语言实现服务器/客户端的TCP通信"/>
<meta name="twitter:description" content="本文力求使用简单的描述说明一个服务器/客户端TCP通信的基本程序框架，使读者在这个框架下可以构建更加复杂的服务，文中给出了服务器端和客户端的实例源程序，本文适合网络编程的初学者阅读；本文的程序在ubuntu 20.04中编译运行成功，gcc版本号为：9.4.0"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

  <script async src="/js/busuanzi.pure.mini.js"></script><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9724909319263152"
     crossorigin="anonymous"></script>


</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">WhoWin</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">文章归档</li>
      </a><a href="/article-categories/categories/">
        <li class="mobile-menu-item">文章分类</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">文章标签</li>
      </a><a href="/about/about/">
        <li class="mobile-menu-item">关于</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">WhoWin</a>
  
  <div style="position:absolute; left: 80px; top: 75px; color: crimson">
      ———开源和分享是技术发展的源泉和动力；本博客所有文章均为原创
  </div>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">文章归档</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/article-categories/categories/">文章分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">文章标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/about/about/">关于</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">使用C语言实现服务器/客户端的TCP通信</h1>

      <div class="post-meta">
        <span class="post-time"> 2023-01-06 </span>
        <div class="post-category">
            <a href="/categories/linux/"> Linux </a>
            <a href="/categories/c-language/"> C Language </a>
            <a href="/categories/network/"> Network </a>
            </div>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#1-前言">1. 前言</a></li>
        <li><a href="#2-服务器客户端tcp通信的基本流程">2. 服务器/客户端TCP通信的基本流程</a></li>
        <li><a href="#3-tcp编程常用的函数和数据结构">3. TCP编程常用的函数和数据结构</a></li>
        <li><a href="#4-服务器客户端tcp通信的实例">4. 服务器/客户端TCP通信的实例</a></li>
        <li><a href="#5-后记">5. 后记</a></li>
        <li><a href="#欢迎订阅-网络编程专栏httpsblogcsdnnetwhowincategory_12180345html"><strong>欢迎订阅 <a href="https://blog.csdn.net/whowin/category_12180345.html">『网络编程专栏』</a></strong></a></li>
      </ul>
    </li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p>本文力求使用简单的描述说明一个服务器/客户端TCP通信的基本程序框架，使读者在这个框架下可以构建更加复杂的服务，文中给出了服务器端和客户端的实例源程序，本文适合网络编程的初学者阅读；本文的程序在ubuntu 20.04中编译运行成功，gcc版本号为：9.4.0</p>
<h2 id="1-前言">1. 前言</h2>
<blockquote>
<p>当两台主机间需要通信时，TCP和UDP是两种最常用的传输层协议，TCP是一种面向连接的传输协议，常用于对传输可靠性要求比较高的场合，比如传输文件；而UDP是一种无连接的通信方式，用于传输一些要求速度快，但对可靠性要求不高的场合，比如实时视频的传输；</p>
</blockquote>
<blockquote>
<p>所谓面向连接指的是在进行传输数据之前要确保进行通信的两台主机已经建立起了连接，比如A机和B机进行TCP通信，A发起通信时要首先连接B机，连接建立起来以后才能够进行数据传输(发送和接收数据)，如果无法建立连接(比如B机没有开机)则不能进行数据传输；TCP协议有完善的错误检查和错误恢复的能力，能够保证数据完好无损地传输到目的地；</p>
</blockquote>
<blockquote>
<p>所谓面向无连接指的是在传输数据之前无须在两台进行通信的主机之间建立连接，直接发送数据即可，带来的问题是如果需要通信的两台主机如果其中有一台没有连接在网络上，那么发送的数据肯定是不能到达目的地的，同样，UDP协议没有完善的纠错机制，所以如果传输过程中出现错误，出错的数据包会被丢弃，导致数据没有到达目的地或者到达目的地的数据不完整；</p>
</blockquote>
<blockquote>
<p>相比较UDP通信，TCP通信对资源要求的要多一些，所以传输速度比起UDP就要慢一些，但其高可靠性的特点使得很多应用层的协议都是基于TCP协议的，比如：HTTP、HTTPS、FTP、SMTP、ssh等；</p>
</blockquote>
<blockquote>
<p>基于TCP协议的一次通信需要三个socket，服务器端建立一个server_sock监听一个特定端口，客户端建立一个client_sock向服务器发起连接请求，服务器端接受连接并生成一个新的connect_sock与该客户端进行通信。</p>
</blockquote>
<h2 id="2-服务器客户端tcp通信的基本流程">2. 服务器/客户端TCP通信的基本流程</h2>
<ul>
<li>
<p><strong>服务端流程</strong></p>
<ol>
<li>使用socket()，创建一个TCP Socket；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">int</span> <span class="n">sockfd</span> <span class="o">=</span> <span class="n">socket</span><span class="p">(</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">SOCK_STREAM</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="2">
<li>将socket设置为可重用的状态</li>
</ol>
<blockquote>
<p>这个server只能通过ctrl+c退出，尽管程序中拦截了ctrl+c的信号，在退出之前关闭了打开的socket，以防万一，仍然将socket设置为可重用比较好，这样保证ctrl+c退出后可以马上再进入；</p>
</blockquote>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">const</span> <span class="kt">int</span> <span class="n">reuseaddr_flag</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">setsockopt</span><span class="p">(</span><span class="n">sockfd</span><span class="p">,</span> <span class="n">SOL_SOCKET</span><span class="p">,</span> <span class="n">SO_REUSEADDR</span><span class="p">,</span> <span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">reuseaddr_flag</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">reuseaddr_flag</span><span class="p">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="3">
<li>使用bind()，将socket绑定到服务器地址上；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="cp">#define PORT            8080
</span></span></span><span class="line"><span class="cl"><span class="cp"></span><span class="k">struct</span> <span class="n">sockaddr</span> <span class="n">server_addr</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">bzero</span><span class="p">(</span><span class="o">&amp;</span><span class="n">server_addr</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">server_addr</span><span class="p">));</span>
</span></span><span class="line"><span class="cl"><span class="n">server_addr</span><span class="p">.</span><span class="n">sin_family</span>      <span class="o">=</span> <span class="n">AF_INET</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">server_addr</span><span class="p">.</span><span class="n">sin_addr</span><span class="p">.</span><span class="n">s_addr</span> <span class="o">=</span> <span class="n">htonl</span><span class="p">(</span><span class="n">INADDR_ANY</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="n">server_addr</span><span class="p">.</span><span class="n">sin_port</span>        <span class="o">=</span> <span class="n">htons</span><span class="p">(</span><span class="n">PORT</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">bind</span><span class="p">(</span><span class="n">sockfd</span><span class="p">,</span> <span class="p">(</span><span class="k">const</span> <span class="k">struct</span> <span class="n">sockaddr</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">server_addr</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">server_addr</span><span class="p">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="4">
<li>使用listen()，在绑定的服务器地址上监听，等待从客户端发送的连接请求；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">listen</span><span class="p">(</span><span class="n">sockfd</span><span class="p">,</span> <span class="mi">5</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="5">
<li>拦截ctrl+c的信号，保证程序可以干净地退出</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">void</span> <span class="nf">sigint</span><span class="p">(</span><span class="kt">int</span> <span class="n">signum</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="n">connfd</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="n">close</span><span class="p">(</span><span class="n">connfd</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="n">sockfd</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="n">close</span><span class="p">(</span><span class="n">sockfd</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">    <span class="n">exit</span><span class="p">(</span><span class="n">EXIT_FAILURE</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">......</span>
</span></span><span class="line"><span class="cl"><span class="n">signal</span><span class="p">(</span><span class="n">SIGINT</span><span class="p">,</span> <span class="n">sigint</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="6">
<li>使用accept()，接受从客户端发来的连接请求，建立连接，并生成一个面向该连接的socket；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">int</span> <span class="n">connfd</span> <span class="o">=</span> <span class="n">accept</span><span class="p">(</span><span class="n">sockfd</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="7">
<li>使用read()；在新socket上接收从客户端发来的信息；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="cp">#define BUF_SIZE    128
</span></span></span><span class="line"><span class="cl"><span class="cp"></span><span class="kt">char</span> <span class="n">buff</span><span class="p">[</span><span class="n">BUF_SIZE</span><span class="p">];</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">bzero</span><span class="p">(</span><span class="n">buff</span><span class="p">,</span> <span class="n">BUF_SIZE</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="n">read</span><span class="p">(</span><span class="n">connfd</span><span class="p">,</span> <span class="n">buff</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">buff</span><span class="p">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="8">
<li>向客户端发送(write)从键盘输入的信息，如有必要，回到步骤7；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">bzero</span><span class="p">(</span><span class="n">buff</span><span class="p">,</span> <span class="n">BUF_SIZE</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="kt">int</span> <span class="n">n</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="k">while</span> <span class="p">((</span><span class="n">buff</span><span class="p">[</span><span class="n">n</span><span class="o">++</span><span class="p">]</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">())</span> <span class="o">!=</span> <span class="sc">&#39;\n&#39;</span> <span class="o">&amp;&amp;</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="n">BUF_SIZE</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">write</span><span class="p">(</span><span class="n">connfd</span><span class="p">,</span> <span class="n">buff</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">buff</span><span class="p">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="9">
<li>关闭与客户端的连接；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">close</span><span class="p">(</span><span class="n">connfd</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="10">
<li>返回步骤6。</li>
</ol>
</li>
</ul>
<hr>
<ul>
<li><strong>客户端流程</strong>
<ol>
<li>使用socket()，创建一个TCP Socket；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">int</span> <span class="n">sockfd</span> <span class="o">=</span> <span class="n">socket</span><span class="p">(</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">SOCK_STREAM</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="2">
<li>使用connect()，向服务器发起连接请求；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="cp">#define SERVER_IP     192.168.2.112
</span></span></span><span class="line"><span class="cl"><span class="cp">#define PORT          8080
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>
</span></span><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">sockaddr_in</span> <span class="n">server_addr</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">bzero</span><span class="p">(</span><span class="o">&amp;</span><span class="n">server_addr</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">server_addr</span><span class="p">));</span>
</span></span><span class="line"><span class="cl"><span class="n">server_addr</span><span class="p">.</span><span class="n">sin_family</span>      <span class="o">=</span> <span class="n">AF_INET</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">server_addr</span><span class="p">.</span><span class="n">sin_addr</span><span class="p">.</span><span class="n">s_addr</span> <span class="o">=</span> <span class="n">inet_addr</span><span class="p">(</span><span class="n">SERVER_IP</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="n">server_addr</span><span class="p">.</span><span class="n">sin_port</span>        <span class="o">=</span> <span class="n">htons</span><span class="p">(</span><span class="n">PORT</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">connect</span><span class="p">(</span><span class="n">sockfd</span><span class="p">,</span> <span class="p">(</span><span class="k">struct</span> <span class="n">sockaddr</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">server_addr</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">server_addr</span><span class="p">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="3">
<li>使用write()，向服务器发送从键盘输入的消息；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="cp">#define BUF_SIZE    128
</span></span></span><span class="line"><span class="cl"><span class="cp"></span><span class="kt">char</span> <span class="n">buff</span><span class="p">[</span><span class="n">BUF_SIZE</span><span class="p">];</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">bzero</span><span class="p">(</span><span class="n">buff</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">buff</span><span class="p">));</span>
</span></span><span class="line"><span class="cl"><span class="kt">int</span> <span class="n">n</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="c1">// get the mesage from keyboard. end with return.
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">while</span> <span class="p">((</span><span class="n">buff</span><span class="p">[</span><span class="n">n</span><span class="o">++</span><span class="p">]</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">())</span> <span class="o">!=</span> <span class="sc">&#39;\n&#39;</span> <span class="o">&amp;&amp;</span> <span class="n">n</span> <span class="o">&lt;</span> <span class="n">BUF_SIZE</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">write</span><span class="p">(</span><span class="n">sockfd</span><span class="p">,</span> <span class="n">buff</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">buff</span><span class="p">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="4">
<li>使用read()，等待接收服务器的回复；</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">bzero</span><span class="p">(</span><span class="n">buff</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">buff</span><span class="p">));</span>
</span></span><span class="line"><span class="cl"><span class="n">read</span><span class="p">(</span><span class="n">sockfd</span><span class="p">,</span> <span class="n">buff</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">buff</span><span class="p">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ol start="5">
<li>处理收到的服务器端回复，如有必要，返回第3步。</li>
<li>关闭Socket并退出。</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">close</span><span class="p">(</span><span class="n">sockfd</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
</ul>
<h2 id="3-tcp编程常用的函数和数据结构">3. TCP编程常用的函数和数据结构</h2>
<ul>
<li>
<p><strong>int socket(int domain, int type, int protocol)</strong></p>
<ul>
<li>建立一个没有绑定地址的socket，返回socket文件描述符</li>
<li>参数说明：
<ol>
<li>domain: 协议族；IPv4为AF_INET，IPv6为AF_INET6</li>
<li>type：socket的传输方式；TCP为SOCK_STREAM，UDP为SOCK_DGRAM</li>
<li>protocol：指定socket使用的协议；通常情况下，一个协议族只支持一种协议，所以通常将protocol置为0，让系统选择匹配的协议；</li>
</ol>
</li>
</ul>
</li>
<li>
<p><strong>int bind(int sockfd, (const struct sockaddr *)addr, socklen_t addrlen)</strong></p>
<ul>
<li>为未绑定地址的socket分配地址</li>
<li>参数说明
<ol>
<li>sockfd：要绑定的socket的文件描述符</li>
<li>addr：绑定的地址(后面会介绍struct sockaddr)</li>
<li>addrlen：addr结构的大小</li>
</ol>
</li>
</ul>
</li>
<li>
<p><strong>int listen(int sockfd, int backlog)</strong></p>
<ul>
<li>在一个已经绑定了地址的socket上侦听</li>
<li>参数说明：
<ol>
<li>sockfd：已经绑定好地址的socket文件描述符</li>
<li>backlog：侦听队列的最大长度；也就是等待处理的连接请求的最大数量</li>
</ol>
</li>
</ul>
</li>
<li>
<p><strong>int connect(int sockfd, (const struct sockaddr *)addr, socklen_t addrlen)</strong></p>
<ul>
<li>创建与指定地址的连接；</li>
<li>参数说明：
<ol>
<li>sockfd：socket文件描述符</li>
<li>addr：建立连接的地址结构，struct sockaddr结构在后面介绍</li>
<li>addrlen：地址结构的大小</li>
</ol>
</li>
</ul>
</li>
<li>
<p><strong>int accept(int sockfd, (struct sockaddr *)addr, socklen_t *addrlen)</strong></p>
<ul>
<li>在指定的socket上接受一个连接请求</li>
<li>参数说明：
<ol>
<li>sockfd：socket文件描述符</li>
<li>addr：建立连接的地址结构，struct sockaddr结构在后面介绍</li>
<li>addrlen：地址结构的大小，注意这里参数是一个指针，与connect()不同</li>
</ol>
</li>
<li>调用这个函数时，addr和addrlen在调用成功后将被填写好对端的地址和端口信息，所以在调用前最好将其清0；如果我们并不关心对端的地址信息，这两个参数其实也可以为NULL；</li>
</ul>
</li>
<li>
<p><strong>ssize_t read(int fd, void *buf, size_t count)</strong></p>
<ul>
<li>从指定文件描述符中读出内容到缓冲区中</li>
<li>参数说明：
<ol>
<li>fd：文件描述符(本文中为socket文件描述符)</li>
<li>buf：存放读出内容的缓冲区</li>
<li>count：buf的大小</li>
</ol>
</li>
</ul>
</li>
<li>
<p><strong>ssize_t write(int fd, (const void *)buf, size_t count)</strong></p>
<ul>
<li>将缓冲区内容写入指定文件描述符中</li>
<li>参数说明：
<ol>
<li>fd：文件描述符(本文中为socket文件描述符)</li>
<li>buf：存放写入内容的缓冲区</li>
<li>count：需要写入内容的长度</li>
</ol>
</li>
</ul>
</li>
<li>
<p><strong>int close(int fd);</strong></p>
<ul>
<li>关闭一个文件描述符</li>
<li>参数说明：
<ol>
<li>fd：文件描述符(本文中是一个socket文件描述符)</li>
</ol>
</li>
</ul>
</li>
<li>
<p>结构<strong>struct sockaddr</strong> - 定义在bits/socket.h</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">sockaddr</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">__SOCKADDR_COMMON</span> <span class="p">(</span><span class="n">sa_</span><span class="p">);</span>  <span class="cm">/* Common data: address family and length.  */</span>
</span></span><span class="line"><span class="cl">    <span class="kt">char</span> <span class="n">sa_data</span><span class="p">[</span><span class="mi">14</span><span class="p">];</span>         <span class="cm">/* Address data.  */</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span></code></pre></td></tr></table>
</div>
</div><blockquote>
<p>通常情况下，做socket编程时，我们只会include &lt;sys/socket.h&gt;，sys/socket.h中会include &lt;bits/socket.h&gt;；在(struct sockaddr)结构中的宏__SOCKADDR_COMMON展开后就是(sa_family_t sa_family)，sa_family_t是一个类型定义，实际为：unsigned short，所以(struct sockaddr)的结构为：</p>
</blockquote>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">sockaddr</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">sa_family_t</span> <span class="n">sa_family</span><span class="p">;</span>  <span class="cm">/* Common data: address family and length.  */</span>
</span></span><span class="line"><span class="cl">    <span class="kt">char</span> <span class="n">sa_data</span><span class="p">[</span><span class="mi">14</span><span class="p">];</span>       <span class="cm">/* Address data.  */</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span></code></pre></td></tr></table>
</div>
</div><blockquote>
<p>这个结构用做bind、recvfrom、sendto等函数的参数，指明地址信息，但实际编程中并不直接针对此数据结构操作，因为针对不同的协议族，地址信息是不同的，比如对于IPv4(AF_INET)，使用(struct sockaddr_in)，这个结构和sockaddr是等价的，但是把sockaddr中的sa_data部分做了更明确的定义；当协议族为IPv6(AF_INET6)时，使用(struct sockaddr_in6)来表示IPv6的地址；</p>
</blockquote>
<blockquote>
<p>在使用这个结构作为函数参数时，通常需要传递地址结构的指针，而且还需要传递这个地址结构的长度，比如sendto()函数的定义为：ssize_t sendto(int sockfd, (const void *)buf, size_t len, int flags, (const struct sockaddr *)dest_addr, socklen_t addrlen)；其中最后一个参数addrlen就是地址结构dest_addr的长度，这是因为对不同的协议族，使用的地址结构不同，这个地址结构的长度也是不同的，比如IPv4使用的地址结构(struct sockaddr_in)和IPv6使用的地址结构(struct sockaddr_in6)的长度就不同。</p>
</blockquote>
</li>
<li>
<p>结构<strong>struct sockaddr_in</strong> - 定义在netinet/in.h</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">sockaddr_in</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">__SOCKADDR_COMMON</span> <span class="p">(</span><span class="n">sin_</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">    <span class="n">in_port_t</span> <span class="n">sin_port</span><span class="p">;</span>           <span class="cm">/* Port number.  */</span>
</span></span><span class="line"><span class="cl">    <span class="k">struct</span> <span class="n">in_addr</span> <span class="n">sin_addr</span><span class="p">;</span>      <span class="cm">/* Internet address.  */</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="cm">/* Pad to size of `struct sockaddr&#39;.  */</span>
</span></span><span class="line"><span class="cl">    <span class="kt">unsigned</span> <span class="kt">char</span> <span class="n">sin_zero</span><span class="p">[</span><span class="k">sizeof</span> <span class="p">(</span><span class="k">struct</span> <span class="n">sockaddr</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="o">-</span> <span class="n">__SOCKADDR_COMMON_SIZE</span>
</span></span><span class="line"><span class="cl">        <span class="o">-</span> <span class="k">sizeof</span> <span class="p">(</span><span class="n">in_port_t</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="o">-</span> <span class="k">sizeof</span> <span class="p">(</span><span class="k">struct</span> <span class="n">in_addr</span><span class="p">)];</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span></code></pre></td></tr></table>
</div>
</div><blockquote>
<p>当协议族为IPv4时，使用这个结构来指明地址信息，就本文而言，有两个地方需要用到这个结构：</p>
</blockquote>
<ol>
<li>服务器端程序在socket绑定服务器地址信息时，需要填写这个结构并作为参数传递给bind()函数；</li>
<li>客户端程序，在需要向服务器发起连接时，需要填写这个结构并作为参数传递给connect()函数；</li>
</ol>
<blockquote>
<p>这个结构中只有三个字段，</p>
</blockquote>
<ol>
<li>sin_family: 协议族，IPv4下填AF_INET</li>
<li>sin_port: 端口号；存储为网络字节顺序，所以需要使用htons()转换一下，比如htons(8080)；</li>
<li>sin_addr：这是一个结构(struct in_addr)，这个结构中只有一个字段s_addr，这是一个32位的IP地址，对于通常使用的字符串IP地址，需要用inet_addr()转换一下，见下面例子：</li>
</ol>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">sockaddr_in</span> <span class="n">addr</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">addr</span><span class="p">.</span><span class="n">sin_addr</span><span class="p">.</span><span class="n">s_addr</span> <span class="o">=</span> <span class="n">inet_addr</span><span class="p">(</span><span class="s">&#34;192.168.1.10&#34;</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
</ul>
<h2 id="4-服务器客户端tcp通信的实例">4. 服务器/客户端TCP通信的实例</h2>
<ul>
<li>
<p>这个实例是一个服务器和客户端聊天的程序，大致运行流程如下：</p>
<ol>
<li>服务器端程序启动后侦听在8080端口上；</li>
<li>客户端程序启动后向服务器发起连接请求；</li>
<li>服务器端程序接受连接并建立一个新的socket；</li>
<li>客户端从键盘输入要发送到服务器端的信息，以回车结束，并将信息发到服务器；</li>
<li>服务器端收到客户端发来的信息，并要求键盘输入回应信息，以回车结束，并将信息发向客户端；</li>
<li>循环步骤4、5，直至服务器端在键盘输入&quot;exit&quot;并且向客户端发送&quot;exit&quot;；</li>
<li>服务器端在键盘输入&quot;exit&quot;并发往客户端后退出聊天，并继续侦听在8080端口上；</li>
<li>客户端在收到服务器端发来的&quot;exit&quot;后退出程序。</li>
</ol>
</li>
<li>
<p>这两个程序表达了编写一个服务器/客户端TCP通信程序的基本框架，实际使用还需要添加许多代码；</p>
</li>
<li>
<p>这两个程序在ubuntu 20.04下编译运行成功；</p>
</li>
<li>
<p>服务器端程序：<a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/180012/tcp-server.c">tcp-server.c</a>(<strong>点击文件名下载源程序</strong>)</p>
<blockquote>
<p>服务器端程序在绑定地址时绑定的是服务器的地址，端口号是程序侦听的端口，INADDR_ANY这个宏在netinet/in.h中定义，实际上就是一个32位的0，对应的IP地址就是0.0.0.0，和inet_addr(&ldquo;0.0.0.0&rdquo;)是一样的，inet_addr()函数会把一个字符串形式的IP地址转换成一个网络字符顺序的32位的IP地址，这里将IP绑定为0.0.0.0的含义是本机的所有IP地址，一台机器有可能有多个网卡，比如有线网卡和无线网卡，那么这台机器就可能有两个IP地址，加上loopback，就有三个IP地址，假定这三个地址分别是：192.168.2.112(有线网卡)、192.168.2.113(无线网卡)和127.0.0.1(loopback)，如果这里设置成inet_addr(&ldquo;192.168.2.112&rdquo;)，则表示只接收发往目的地址是192.168.2.112这个IP的信息，也就是只接收从有线网卡收到的数据，大家可以试一下；如果绑定的IP地址不是本机的一个合法IP，在执行bind()时会出错；</p>
</blockquote>
<blockquote>
<p>这个服务器端程序同时只能处理一个客户端的连接，尽管在调用listen(sockfd, 5)时允许连接队列里有5个未处理的连接，但实际处理中并不能同时处理多个连接；</p>
</blockquote>
<blockquote>
<p>服务器端程序是没有退出出口的，退出服务器程序的唯一办法是ctrl+c；服务器端程序退出聊天有两种方式，一种是服务器端主动向客户端发送&quot;exit&quot;，第二种是当客户端发来&quot;exit&quot;时，回复&quot;exit&quot;，总之，服务器端向客户端发出&quot;exit&quot;后就可以退出；这个程序只有在退出当前聊天后才能处理下一个连接请求。</p>
</blockquote>
</li>
<li>
<p>编译、运行和测试服务器端程序</p>
<ul>
<li>
<p>编译</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">gcc -Wall tcp-server.c -o tcp-server
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>运行服务器端程序</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">./tcp-server
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>在另一台机器上的终端上运行下面指令模拟客户端，可以进入聊天模式，这里192.168.2.112为运行了tcp-server程序的服务器IP地址</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">nc -n 192.168.2.112 <span class="m">8080</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>有关nc命令的使用方法，可以参考另一篇文章<a href="https://blog.csdn.net/whowin/article/details/128890866">《如何在Linux命令行下发送和接收UDP数据包》</a></p>
</li>
<li>
<p>服务器端程序只能用ctrl+c才能退出；</p>
</li>
<li>
<p>服务器运行截图</p>
<p><img src="https://whowin.gitee.io/images/180012/tcp_server_testing.png" alt="test tcperver with nc"></p>
</li>
</ul>
<hr>
<ul>
<li>
<p>模拟客户端运行截图</p>
<p><img src="https://whowin.gitee.io/images/180012/tcp_netcat_testing.png" alt="test tcpserver with nc"></p>
</li>
</ul>
</li>
</ul>
<hr>
<ul>
<li>
<p>客户端程序：<a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/180012/tcp-client.c">tcp-client.c</a>(<strong>点击文件名下载源程序</strong>)</p>
<blockquote>
<p>客户端程序在发起连接时设置服务器地址，端口号是服务器端程序绑定的端口，192.168.2.112是服务器的IP地址，请根据自身的情况进行修改，IP和端口号必须和服务器一致，否则服务器无法收到信息；</p>
</blockquote>
<blockquote>
<p>必须要首先运行服务器端程序，客户端程序才能运行起来；客户端程序只有收到服务器端发送过来的&quot;exit&quot;才能退出。</p>
</blockquote>
</li>
<li>
<p>客户端程序的编译</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">gcc -Wall tcp-client.c -o tcp-client
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>程序运行</p>
<ul>
<li>
<p>一台机器上运行服务端程序：tcpserver</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">./tcp-server
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>在另一台机器上运行客户端程序：tcp-client</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">./tcp-client
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>进入聊天模式，直至服务器端向客户端发送&quot;exit&quot;</p>
</li>
<li>
<p>客户端程序的运行截图</p>
<p><img src="https://whowin.gitee.io/images/180012/screenshot_tcpclient.png" alt="screenshot of udpclient"></p>
</li>
</ul>
<hr>
<ul>
<li>
<p>服务器端程序的运行截图</p>
<p><img src="https://whowin.gitee.io/images/180012/screenshot_tcpserver.png" alt="screenshot of udpserver"></p>
</li>
</ul>
</li>
</ul>
<hr>
<h2 id="5-后记">5. 后记</h2>
<ul>
<li>从本文的例子看，TCP的服务器/客户端的通信框架并不复杂，但是本文的例子只是一个最基本的框架，并不适合在生产环境下运行；</li>
<li>本文实例中用于发送和接收数据使用了read()和write()两个函数，实际使用中还可以使用send()/recv()或者sendmsg()/recvmsg()等；</li>
<li>对于一个socket还有很多模式可以设置，通常使用fcntl()和setsockopt()进行设置，这些在本文中也没有讨论；</li>
<li>对于服务器端程序，一定会遇到多个客户端同时向服务器端发送连接请求的情况，有多种方法处理这种情况，比如：多线程、select、epoll等；</li>
</ul>
<h2 id="欢迎订阅-网络编程专栏httpsblogcsdnnetwhowincategory_12180345html"><strong>欢迎订阅 <a href="https://blog.csdn.net/whowin/category_12180345.html">『网络编程专栏』</a></strong></h2>
<hr>
<p><strong>欢迎访问我的博客：https://whowin.cn</strong></p>
<p><strong>email: <a href="mailto:hengch@163.com">hengch@163.com</a></strong></p>
<p><img src="https://whowin.gitee.io/images/qrcode/sponsor-qrcode.png" alt="donation"></p>
<!-- CSDN
[img01]:https://img-blog.csdnimg.cn/img_convert/180c46cf82c0610e6ad9774884ccdc38.png
[img02]:https://img-blog.csdnimg.cn/img_convert/22305de32989c318ca3384172bd88729.png
[img03]:https://img-blog.csdnimg.cn/img_convert/0f109838d422eee721d72d3cdb29ff0d.png
[img04]:https://img-blog.csdnimg.cn/img_convert/f3e99f1fc63fcce264d731731cee9c79.png
-->
<!--gitee
[article1]:https://whowin.gitee.io/post/blog/network/0005-send-udp-via-linux-cli/
-->
    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">whowin</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2023-01-06
        
    </span>
  </p>
  
  
</div>
<footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/linux/">Linux</a>
          <a href="/tags/socket/">Socket</a>
          <a href="/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/">网络编程</a>
          <a href="/tags/tcp/">TCP</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/blog/network/0010-tcp-and-udp-server-using-select/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">使用select实现的UDP/TCP组合服务器</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/blog/network/0013-udp-server-client-implementation-in-c/">
            <span class="next-text nav-default">使用C语言实现服务器/客户端的UDP通信</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  <span id="/post/blog/network/0012-tcp-server-client-implementation-in-c/" class="leancloud_visitors" data-flag-title="使用C语言实现服务器/客户端的TCP通信">
		<span class="post-meta-item-text">文章阅读量 </span>
		<span class="leancloud-visitors-count">0</span>
		<p></p>
	  </span>
  <div id="vcomments"></div>
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
  <script type="text/javascript">
    new Valine({
        el: '#vcomments' ,
        appId: 'OFCGzCfJRUglzOdzrqMGkbTR-gzGzoHsz',
        appKey: 'v7P29kPAEbsmaavaYPNhGhnF',
        notify:  false ,
        verify:  false ,
        avatar:'mm',
        placeholder: '说点什么吧...',
        visitor:  true 
    });
  </script>

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:hengch@163.com" class="iconfont icon-email" title="email"></a>
  <a href="https://whowin.gitee.io/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>
<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  <div class="busuanzi-footer">
    <span id="busuanzi_container_site_pv"> 本站总访问量 <span id="busuanzi_value_site_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次 </span>
      <span class="division">|</span>
    <span id="busuanzi_container_site_uv"> 本站总访客数 <span id="busuanzi_value_site_uv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 人 </span>
  </div>

  <span class="copyright-year">
    &copy; 
    2022 - 
    2024<span class="heart"><i class="iconfont icon-heart"></i></span><span>whowin</span>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.64437849d125a2d603b3e71d6de5225d641a32d17168a58106e0b61852079683.js"></script>
  <script type="text/javascript">
    window.MathJax = {
      tex: {
        inlineMath: [['$','$'], ['\\(','\\)']],
        }
    };
  </script>
  <script async src="https://cdn.jsdelivr.net/npm/mathjax@3.0.5/es5/tex-mml-chtml.js" integrity="sha256-HGLuEfFcsUJGhvB8cQ8nr0gai9EucOOaIxFw7qxmd+w=" crossorigin="anonymous"></script>








</body>
</html>
